import logging
import os
import sys
from pathlib import Path

# 创建logs目录（如果不存在）
# LOGS_DIR = Path(__file__).parent / "logs"
# LOGS_DIR.mkdir(exist_ok=True)


def get_log_path():
    """Get the appropriate log file path"""
    if getattr(sys, 'frozen', False):
        # Running as compiled executable
        application_path = os.path.dirname(sys.executable)
    else:
        # Running as script
        application_path = os.path.dirname(os.path.abspath(__file__))

    log_dir = os.path.join(application_path, 'logs')
    os.makedirs(log_dir, exist_ok=True)  # Create logs directory if it doesn't exist
    return os.path.join(log_dir, 'app.log')

def setup_logger(name='ai_talk', level=logging.INFO):
    """
    设置并返回一个logger实例
    
    Args:
        name (str): logger名称
        level: 日志级别
        
    Returns:
        logging.Logger: 配置好的logger实例
    """
    # 创建logger
    logger = logging.getLogger(name)
    logger.setLevel(level)
    
    # 避免重复添加handler
    if logger.handlers:
        return logger
    
    # 创建formatter
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s'
    )
    
    # 创建控制台handler
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setLevel(level)
    console_handler.setFormatter(formatter)
    
    # 创建文件handler
    file_handler = logging.FileHandler(get_log_path(), encoding='utf-8')
    file_handler.setLevel(level)
    file_handler.setFormatter(formatter)
    
    # 添加handlers到logger
    logger.addHandler(console_handler)
    logger.addHandler(file_handler)
    
    return logger


def get_device_logger(device_phone=None,logger_name='ai_talk', level=logging.INFO, **extra_kwargs):

    base_logger = setup_logger(logger_name, level)
    phone = device_phone or ""
    return logging.LoggerAdapter(base_logger, {"device_phone": phone})


# 全局logger实例
logger = setup_logger()